// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main

import (
	"log"
	"strconv"
)

// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
	// Registered clients.
	clients map[*Client]bool
	clis    map[string]*Client
	// Inbound messages from the clients.
	broadcast chan []byte
	// Register requests from the clients.
	register chan *Client
	//register chan *RegData
	// Unregister requests from clients.
	unregister chan *Client
	//定义发送行为
	//--单人发送
	singlePush chan *singleMessage
	//消息来自用户
	userMessage chan *userMessage
	//定义hub标识
	pre string
	//定义当前hub客户端标识
	curId int64
}
type singleMessage struct {
	client  *Client
	message []byte
}
type userMessage struct {
	client  *Client
	message []byte
}
type RegData struct {
	cli   *Client
	token string
}

func newHub() *Hub {
	return &Hub{
		//监听客户端注册
		//register:   make(chan *RegData),
		register: make(chan *Client),
		//监听客户端注销
		unregister: make(chan *Client),
		//储存客户端地址
		clients: make(map[*Client]bool),
		//客户端信息发送监听
		singlePush:  make(chan *singleMessage),
		userMessage: make(chan *userMessage),
		broadcast:   make(chan []byte),
		pre:         "a",
		curId:       10000, //默认从10000开始，做一个预留
		clis:        make(map[string]*Client),
	}
}

func (h *Hub) run() {
	for {
		select {
		case client := <-h.register:
			h.clients[client] = true //todo 准备把这种方式淘汰掉
			//注册用户的时候绑定ID
			clientKey := h.pre + strconv.FormatInt(h.curId, 10)
			client.key = clientKey
			h.clis[clientKey] = client
			h.curId++
		case client := <-h.unregister:
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				close(client.send)
			}
		case userMessage, ok := <-h.userMessage:
			log.Println(ok)
			log.Println("here come to userMessage")
			//接收服务端来的请求
			HandleRead(userMessage.message, h, userMessage.client)
		case message := <-h.broadcast:
			//接收服务端来的请求
			HandleRead(message, h, nil)
		case singlePush := <-h.singlePush:
			singlePush.client.send <- singlePush.message
		}
	}
}
